package com.example.dts.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dts.mapper.FileMapper;
import com.example.dts.mapper.UserMapper;
import com.example.dts.mapper.UserRoleMapper;
import com.example.dts.model.User;
import com.example.dts.model.ro.UserRO;
import com.example.dts.model.vo.LoginVO;
import com.example.dts.model.vo.TokenInfoVO;
import com.example.dts.model.vo.UserVO;
import com.example.dts.repository.UserRepository;
import com.example.dts.service.FileService;
import com.example.dts.service.UserService;
import com.example.dts.type.FileType;
import com.example.dts.utils.DtsException;
import com.example.dts.utils.JwtUtils;
import com.example.dts.utils.SpringUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Optional;
import java.util.UUID;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Value("${avatarPath}")
    private String avatarPath;

    @Value("${domainName}")
    private String domainName;

    @Value("${server.port}")
    private String port;

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserRepository userRepository;

    @Resource
    private SpringUtil springUtil;

    @Resource
    private FileService fileService;

    @Resource
    private FileMapper fileMapper;

    @Override
    public void add(UserRO ro) {
        User user = new User();
        userRepository.findTopByAccount(ro.getAccount()).ifPresent(e -> {
            throw new DtsException(500, "500", "该账号已存在！");
        });
        try {
            BeanUtils.copyProperties(user, ro);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        this.save(user);
    }

    @Override
    public LoginVO login(UserRO ro) {
        QueryWrapper<User> qw = new QueryWrapper<User>();
        qw.eq("account", ro.getAccount());
        User user = Optional.ofNullable(userMapper.selectOne(qw)).orElseThrow(() -> new DtsException(201, "201", "用户不存在"));

        TokenInfoVO tokenInfoVO = new TokenInfoVO();
        tokenInfoVO.setLoginUUID(UUID.randomUUID().toString());
        tokenInfoVO.setAccount(ro.getAccount());
        tokenInfoVO.setUserId(user.getId());
        tokenInfoVO.setRoleName("专家");
        LoginVO vo = new LoginVO();
        vo.setAccount(user.getAccount());
        vo.setToken(JwtUtils.getToken(tokenInfoVO));
        vo.setRoleName("专家");
        vo.setUuid(UUID.randomUUID().toString());
        vo.setUserId(user.getId());
        return vo;
    }

    @Override
    public String uploadAvatar(MultipartFile file, String userId) {
        System.out.println("上传头像");
        String fileName = file.getOriginalFilename();
        File dest = new File(avatarPath + fileName);
        byte environ = springUtil.getEnviron();
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), dest);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String url = "";
        if (environ == 0) {
            url = domainName + ":" + port + avatarPath.substring(16) + fileName;
        } else {
            url = domainName + ":" + port + avatarPath.substring(19) + fileName;
        }
        com.example.dts.model.File file1 = new com.example.dts.model.File();
        file1.setType(FileType.AVATAR);
        file1.setPath(avatarPath);
        file1.setUrl(url);
        file1.setCreateUserId(userId);
        fileService.saveFile(file1, userId);
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",userId);
        updateWrapper.set("avatar_id",file1.getId());
        userMapper.update(null,updateWrapper);
        System.out.println("头像上传成功，头像url：" + url);
        return url;
    }

    @Override
    public UserVO getOne(String account) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);
        UserVO vo = new UserVO();
        User user = this.getOne(queryWrapper);
        try {
            BeanUtils.copyProperties(vo,user);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        QueryWrapper<com.example.dts.model.File> fileQueryWrapper = new QueryWrapper<>();
        fileQueryWrapper.eq("id", user.getAvatarId());
        fileQueryWrapper.eq("deleted",0);
        com.example.dts.model.File avatar = fileMapper.selectOne(fileQueryWrapper);
        vo.setAvatarUrl(avatar.getUrl());
        return vo;
    }
}
